'''
Created on Dec 5, 2010

@author: jackreilly
'''

from google.appengine.ext import db
from jettube.models import getFromJetKey
from django.utils.simplejson import loads
import logging

USER_ID_KEY = 'id'
USER_TYPE_KEY = 'type'
NONE_USER_TYPE = 'none'
PIC_KEY = 'picUrl'
NAME_KEY = 'name'
KEY_KEY = 'userKey'
SESSION_KEY = 'session_key'
STATIONS_KEY = 'stations'
REQUESTED_STATIONS_KEY = 'requestedStations'
BLOCKED_STATIONS_KEY = 'blockedStations'


class User( db.Model ):
    type = db.StringProperty()
    name = db.StringProperty()
    id = db.StringProperty()
    picUrl = db.StringProperty()
    googleUser = db.UserProperty()
    likes = db.StringListProperty()
    dislikes = db.StringListProperty()
    date = db.DateTimeProperty( auto_now_add = True )
    session = db.StringProperty()
    stations = db.ListProperty(item_type=db.Key)
    requestedStations = db.ListProperty(item_type=db.Key)
    blockedStations = db.ListProperty(item_type=db.Key)
    
    def addStationWithPermission(self,station):
        if station.key() in self.blockedStations:
            for i in range(len(self.blockedStations)):
                if self.blockedStations[i] == station.key():
                    del self.blockedStations[i]
        if station.key() in self.stations:
            pass
        elif station.key() not in self.requestedStations:
            self.requestedStations.append(station.key())
        self.put()
        
    def addToStations(self,station):
        self.stations.append(station.key())
        self.put()
        
    def toDict(self):
        try:
            picUrl = self.picUrl
            name = self.name
            key = self.key()
            return {
                PIC_KEY: picUrl,
                KEY_KEY: str(key),
                NAME_KEY:name
                }
        except:
            return {
                PIC_KEY: '',
                KEY_KEY: '',
                NAME_KEY:''
                    }
        
        


def registerExtensionUserFromRequest(request):
    sessionInfo = loads(request.get('session'))
    session_key = sessionInfo['session_key']
    uid = sessionInfo['uid']
    type = 'facebook'
    #This is not secure, need to contact facebook for verification on session, but later
    
    try:
        user = User.get_or_insert(createKeyName(type, uid))
        user.session = session_key
        return True
    except:
        return False
    
    
def createKeyName( type, id ):
    return '%s ::: %s' % ( type, id )


def getChromeExtensionDictionary(request):
    return getExtensionDictionary(getFacebookUserFromSession(request))

def getExtensionDictionary(user):
    from jettube.models import Station
    pubStations = Station.getStationsDictionaryForDropDownFromRequest(None)
    if not user:
        privStations = []
        picUrl = ''
        key = ''
        name = ''
    else:
        privStations = Station.getUserStationsListFromUser(user)
        
        picUrl = user.picUrl
        name = user.name
        key = user.key()
    return {
            'privStations': privStations,
            'pubStations': pubStations,
            'picUrl': picUrl,
            'key': str(key),
            'name':name
            }
    



def getFacebookUserFromSession(request):
    session = getFromJetKey(request, SESSION_KEY)
    if session == 'none':
        return False
    id = getFromJetKey(request, USER_ID_KEY)
    type = 'facebook'
    user = getUserFromIDAndType(id, type)
    if not user.session:
        user.session = session
        user.put()
        return user
    if user.session == session:
        return user
    
    # this needs to be fixed later
    return user
    
def registerRSDecisionFromRequest(request):
    from jettube.models import Station
    user = getUserFromRequest(request)
    station = Station.getStationFromRequest(request)
    stationKey = station.key()
    
    decision = request.get('decision')
    if decision == 'true':
        user.stations.append(stationKey)
    for i in range(len(user.requestedStations)):
        if user.requestedStations[i] == stationKey:
            del user.requestedStations[i]
    user.put()
    
    


def registerUserFromGoogleUser(guser):
    try:
        userid = guser.user_id()
        type = 'google'
        googleUser = guser
        name = guser.nickname()
        newUser = User(key_name = createKeyName(type, userid))
        newUser.type = type
        newUser.id = userid
        newUser.name = name
        newUser.googleUser = googleUser
        newUser.put()
        return newUser.key()
    except:
        return False
    

def registerUserFromRequest(request):
    userid = getFromJetKey(request, USER_ID_KEY)
    type = getFromJetKey(request, USER_TYPE_KEY)
    try:
        newUser = User.get_or_insert(createKeyName(type, userid))
        newUser.picUrl = getFromJetKey(request, PIC_KEY)
        newUser.type = type
        newUser.id = userid
        newUser.name = getFromJetKey(request, NAME_KEY)
        newUser.put()
        return str(newUser.key())
    except:
        return False
    
    
def getUserStationsDictFromRequest(request):
    from jettube.models import Station
    user = getUserFromKey(getFromJetKey(request, KEY_KEY))
    rs = [Station.stationKeyToDict(station) for station in user.requestedStations]
    s = [Station.stationKeyToDict(station) for station in user.stations]
    bs = [Station.stationKeyToDict(station) for station in user.blockedStations]
    return {REQUESTED_STATIONS_KEY:rs,
            STATIONS_KEY:s,
            BLOCKED_STATIONS_KEY:bs}
    
def getUserFromKey(key):
    return User.get(key)


def getUserFromIDAndType(id,type):
    logging.error('reg id: %s' % id)
    logging.error('reg type: %s' % type)
    
    return User.get_or_insert(createKeyName(type, id))

def getUserFromRequest( request ):
    userKey = getFromJetKey(request, KEY_KEY)
    if (not userKey) or (userKey == 'none'):
        return getMasterUser()
    return User.get(userKey)

def getMasterUser():
    userid = 'JetTube'
    usertype = 'JetTube'
    return getUserFromIDAndType(userid, usertype)